package gweb

import (
	"path/filepath"
	"strings"

	"gitee.com/makitdone/gx"
	"github.com/google/uuid"
)

// 日志支持

type LogView struct{}

func (view *LogView) RegisterRoutes(router *RouterGroup) {
	router.POST("/app/log/download", MustBeSuperuser(), view.download)
	router.GET("/app/log/list", MustBeSuperuser(), view.list)
	router.POST("/app/log/detail", MustBeSuperuser(), view.detail)
	router.POST("/app/log/clear", MustBeSuperuser(), view.clear)
}

func (view *LogView) download(c *Context) {
	app := c.App
	dir := app.LogDirectory()
	filename := uuid.New().String()
	filename = filepath.Join(dir, filename+".zip")
	gx.Path(dir).Zip(filename)
	c.FileAttachment(filename, "logs.zip", true)
}

// 获取日志列表
func (view *LogView) list(c *Context) {
	app := c.App
	dir := app.LogDirectory()
	if files, err := gx.Path(dir).Glob("**/*.log"); err != nil {
		c.Error(err.Error())
	} else {
		for i, file := range files {
			files[i] = strings.Replace(file, dir, "", 1)
		}
		c.SuccessWithData(files)
	}
}

func (view *LogView) detail(c *Context) {
	var req struct {
		Filename string `json:"filename"`
	}
	c.ShouldBindJSON(&req)
	app := c.App
	dir := app.LogDirectory()
	filePath := filepath.Join(dir, req.Filename)
	if !gx.Path(filePath).IsFile() {
		c.Error("Log file not found")
		return
	}
	content, err := gx.Path(filePath).ReadAll()
	if err != nil {
		c.Error(err.Error())
		return
	}
	c.SuccessWithData(string(content))
}

func (view *LogView) clear(c *Context) {
	dir := c.App.LogDirectory()
	if err := gx.Path(dir).RemoveAll(); err != nil {
		c.Error(err.Error())
	}
	c.Success()
}
